package packet

import (
	"encoding/hex"
	"fmt"
	"github.com/axgle/mahonia"
	"hy_808/protocol/hygprs"
	"hy_808/util"
	"strings"
	"time"
)

type PA072 struct {
	hygprs.Fields
}

func GenA072Packet(line, bus, operator uint32, cmd byte, ftpAddr string, ftpUser, ftpPassword, ymd, his string) PA072 {
	data, _ := hex.DecodeString(strings.ReplaceAll("A0 00 65 02 00 1D 72 01 00 00 00 34 02 00 00 0A 4D 04 00 00 00 00 06 63 4D 85 8B 43 E5 48 7B E8 26 0A 4B 00 54 46 73 64 68 79 47 73 64 68 79 49 20 22 08 13 42 15 09 40 92 45 01 1A 01 12 01 33 35 32 30 2D 56 35 2E 31 2D 32 30 32 32 30 38 31 31 2D D0 C2 D3 B2 C5 CC B8 F1 CA BD 2E 7A 69 70 00 00 1A FD A1", " ", ""))
	p := PA072{hygprs.MakeFields(hygprs.MakePacket(data))}
	p.SetSerialNumber() //设置包序号
	p.SetLineID(line)
	p.SetBusID(bus)
	p.SetOperatorID(operator)
	p.SetUnix(uint32(time.Now().Unix()))
	//43项 1:程序升级
	p.SetByte(0x43, cmd)
	ftpAddrs := util.AddrToByte4(ftpAddr)
	fmt.Println("组包ftpIP", ftpAddr, hex.EncodeToString(ftpAddrs))
	//FTP服务器IP地址 4个字节IP
	p.SetBytes(0x48, ftpAddrs[:4])
	//FTP服务器端口 4个字节
	p.SetBytes(0x4b, ftpAddrs[4:])

	enc := mahonia.NewDecoder("GBK")
	//ftp用户名
	ftpUserGBK := enc.ConvertString(ftpUser)
	//ftp密码
	ftpPasswordGBK := enc.ConvertString(ftpPassword)
	if len([]byte(ftpUserGBK)) <= 4 && len([]byte(ftpPasswordGBK)) <= 4 {
		p.SetBytes(0x46, util.StrToBytesWithFill(ftpUserGBK, 4, "left", 0))
		p.SetBytes(0x47, util.StrToBytesWithFill(ftpPasswordGBK, 4, "left", 0))
		p.SetBytes(0x12, []byte{})
	} else {
		p.SetBytes(0x46, []byte{0xff, 0xff, 0xff, 0xff})
		p.SetBytes(0x47, []byte{0xff, 0xff, 0xff, 0xff})
		str12 := enc.ConvertString(fmt.Sprintf("userL:%d%s;pswordL:%d%s", len(ftpUser), ftpUser, len(ftpPassword), ftpPassword))
		p.SetBytes(0x12, []byte(str12))
		//p.SetBytes()
	}
	//年月日
	ymdBytes := util.Number2bcd(ymd)
	p.SetBytes(0x49, ymdBytes)
	//时分秒 (秒暂未启用，后两个字节置为0)
	//his = his + "00"
	hiBytes := util.Number2bcd(his)
	fmt.Println("版本号", hex.EncodeToString(ymdBytes), hex.EncodeToString(hiBytes))
	p.SetBytes(0x42, hiBytes)
	//文件分割数
	p.SetByte(0x45, 1)
	//是否需要回应
	p.SetByte(hygprs.AnswerType, 1)

	p.Pack()
	return p
}
